package com.example.usercenter.sys.web;

import com.alibaba.fastjson.JSONObject;
import com.example.usercenter.common.base.ResponseData;
import com.example.usercenter.sys.entity.OrgUser;
import com.example.usercenter.sys.entity.User;
import com.example.usercenter.sys.service.UserService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.usercenter.common.base.BaseRestController;
import com.example.usercenter.common.base.BaseService;
import com.example.usercenter.sys.service.OrgService;
import com.example.usercenter.sys.entity.Org;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/org")
public class OrgController extends BaseRestController<Org, Long> {
    @Autowired
    private OrgService orgService;
    @Autowired
    private UserService userService;

    protected BaseService<Org, Long> getService(){
            return orgService;
    }

    private final static String ORG_SUPER = "ORG_SUPER";

    @Override
    @PreAuthorize("hasAuthority('ORG')")
    public ResponseData get(@PathVariable("id") Long id) {
        return super.get(id);
    }

    @Override
    @Secured({"ORG", ORG_SUPER})
    public ResponseData save(@RequestBody Org entity) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth.getAuthorities().contains(new SimpleGrantedAuthority(ORG_SUPER))){
            return super.save(entity);
        }
        else{
            User user = (User) auth.getPrincipal();
            List<Org> orgs = orgService.getOrgsByUser(user, "ORG");
            List<Long> orgIds = orgs.stream().map(org -> org.getId()).collect(Collectors.toList());
            if(entity.getParent()!=null && entity.getParent().getId()>0 && orgIds.contains(entity.getParent().getId())){
                return super.save(entity);
            }
            return ResponseData.fail("用户无权限添加该组织");
        }
    }

    @Override
    @Secured({"ORG", ORG_SUPER})
    public ResponseData update(@RequestBody Org entity) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth.getAuthorities().contains(new SimpleGrantedAuthority(ORG_SUPER))){
            return super.update(entity);
        }
        else{
            User user = (User) auth.getPrincipal();
            List<Org> orgs = orgService.getOrgsByUser(user, "ORG");
            List<Long> orgIds = orgs.stream().map(org -> org.getId()).collect(Collectors.toList());
            if(orgIds.contains(entity.getId()))
                return super.update(entity);
            else
                return ResponseData.fail("用户无权限修改该组织");
        }
    }

    @Override
    @Secured({"ORG", ORG_SUPER})
    public ResponseData delete(@PathVariable("id") Long id) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth.getAuthorities().contains(new SimpleGrantedAuthority(ORG_SUPER))){
            return super.delete(id);
        }
        else{
            User user = (User) auth.getPrincipal();
            List<Org> orgs = orgService.getOrgsByUser(user, "ORG");
            List<Long> orgIds = orgs.stream().map(org -> org.getId()).collect(Collectors.toList());
            if(orgIds.contains(id))
                return super.delete(id);
            else
                return ResponseData.fail("用户无权限删除该组织");
        }
    }

    @Override
    @PreAuthorize("hasAuthority('ORG')")
    public ResponseData page(@RequestBody JSONObject params) {
        return super.page(params);
    }

    @Override
    @Secured({"ORG"})
    public ResponseData query(@RequestBody JSONObject params) {
        return super.query(params);
    }

    @RequestMapping(value = "/queryByUser")
    @Secured({"ORG", "USER", ORG_SUPER})
    public ResponseData queryByUser(@RequestBody JSONObject params) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if(auth.getAuthorities().contains(new SimpleGrantedAuthority(ORG_SUPER))){
            return super.query(params);
        }
        else{
            User user = (User) auth.getPrincipal();
            return ResponseData.ok("查询列表成功", orgService.getOrgsByUser(user, params.getString("authCode")));
        }
    }

    @PreAuthorize("hasAuthority('ORG')")
    @Override
    public ResponseData exists(@RequestBody JSONObject params) {
        return super.exists(params);
    }
}